package com.base.api;

import cn.hutool.core.util.RandomUtil;

import com.base.config.Const;
import com.base.core.constant.Constants;
import com.base.core.model.ApiRes;
import com.base.core.constant.Enums;
import com.base.core.model.EmailData;
import com.base.core.utils.DateTimeUtil;
import com.base.core.utils.RedisCache;
import com.base.core.utils.SendSingle;
import com.base.service.MailService;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: ly
 * @Date: 2020-11-21
 */
@Api(tags = "短信发送")
@RestController
@Log4j2
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MailService mailService;

    /**
     * 短信验证码发送
     *
     * @param phone
     * @return
     */
    @ApiOperation("发送短信验证码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone", required = true, dataType = "String", paramType = "path"),
    })
    @GetMapping(value = "/send/{phone}")
    public ApiRes generalSms(@PathVariable("phone") String phone) {

        if (StringUtils.isBlank(phone)) {
            return ApiRes.failed(Enums.ResponseStatus.MISS_DATA);
        }

        //六位验证码
        String smsCode = RandomUtil.randomNumbers(6);

        String smsText = "【XXX】您的验证码是：#code#。请在页面中提交验证码完成验证，此验证码#timeout#分钟内有效。";

        //短信发送
        Result<SmsSingleSend> result = SendSingle.yunPianSms(smsText, smsCode, phone, 5);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()

        //获取短信发送返回码
        Integer code = result.getCode();

        if (Objects.isNull(result) || code != 0) {
            log.warn("【短信】手机号：{} 验证码：{} 描述：{}", phone, smsCode, result.getDetail());
            return ApiRes.failed("短信发送失败");
        } else if (code == 0) {
            log.info("【短信】手机号：{} 验证码：{} 描述：{}", phone, smsCode, result.getMsg());
        }

        //将验证码存入redis 有效期 5 分钟
        redisCache.setCacheObject(Constants.PHONE_CODE_KEY + phone, smsCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        return ApiRes.success();
    }

    @ApiOperation("发送邮箱验证码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "email", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "type", required = true, dataType = "Integer", paramType = "path"),
    })
    @GetMapping(value = "/email/{email}/{type}")
    public ApiRes generalEmailCode(@PathVariable("email") String email, @PathVariable("type") Integer type) {

        if (StringUtils.isBlank(email)) {
            return ApiRes.failed(Enums.ResponseStatus.EMAIL_IS_BLANK);
        }

        //六位验证码
        String smsCode = RandomUtil.randomNumbers(6);
        //验证码发送
        EmailData emailData = new EmailData.Builder().setTo(email).setSubject("邮箱验证码").build();
        Map<String, Object> data = new HashMap<>(16);
        data.put("email", email);
        data.put("emailCode", smsCode);
        data.put("codeType", Enums.VerifyCode.getCodeDesc(type));
        data.put("createTime", DateTimeUtil.nowDateTimeStr1());
        try {
            mailService.sendTemplate(emailData, data, Constants.EMAIL_REGISTER_CODE_TEMPLATE_NAME).doIt();
        } catch (MessagingException e) {
            e.printStackTrace();
            log.warn("【验证码发送失败】内容：{} 验证码：{} 描述：{}", email, smsCode, e);
        }
        log.info("【验证码发送】邮箱：{} 验证码：{} 描述：{}", email, smsCode, Enums.VerifyCode.getCodeDesc(type));

        //将验证码存入redis 有效期 2 分钟
        // redisCache.setCacheObject(Constants.EMAIL_CODE_KEY + type + ":" + email, smsCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        return ApiRes.success();
    }
}
